#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

using namespace std;
//父读，子写。
int main()
{
	int fds[2]={0};
	int n=pipe(fds);//创建管道成功
	if(n!=0)//失败
	{
		cerr<<"pipe error"<<endl;
		return 1;	
	}

	//2.创建子进程
	pid_t pid=fork();
	if(pid<0)
	{
		cerr<<"fork error"<<endl;
		return 2;
	}
	else if(pid==0)
	{
		//子进程
		close(fds[0]);

		string message="nihao";
		write(fds[1],message.c_str(),message.size());
		close(fds[1]);
		exit(0);
		//
	}
	else
	{
		//主进程
		pid_t rid=waitpid(pid,nullptr,0);
		close(fds[1]);
		//读取数据
		char buffer[1024];
		ssize_t n=read(fds[0],buffer,1024);
		if(n>0)
		{
			buffer[n]=0;
			cout<<"father wait child success"<<buffer<<endl;
			close(fds[0]);
			exit(0);
		}

	}
	return 0;
}
